<?php


function fetch_used_thing_results($thing) {
  $query = "SELECT user_{$thing}.{$thing}_id, all_{$thing}s.{$thing} FROM user_{$thing}, all_{$thing}s  WHERE user_{$thing}.{$thing}_id=all_{$thing}s.{$thing}_id  GROUP BY {$thing}";
  $result = mysql_query($query)  or trigger_error("Query: $query\n<br />MySQL Error: " . mysql_error());
  return $result;
}

function get_chosen_things($thing, &$tables, &$join, &$ins, &$do_search) {
  if (isset($_POST[$thing]) && count($_POST[$thing])> 0) {
    $in_vals = "(";
    $first=TRUE;
    foreach ($_POST[$thing] as $subj) {
      if (! $first) { $in_vals .= ", ";}
      $in_vals .= "$subj";
      $first= false;
    }
    $in_vals .= ")";
    $query2 = "SELECT $thing FROM all_{$thing}s WHERE {$thing}_id IN $in_vals ORDER BY {$thing}";
    if ($do_search) {
      $join .= " AND ";
      $ins .= " OR ";
    }
    $tables .= ", user_{$thing}";
    $join .= "user_details.user_id = user_{$thing}.user_id ";
    $ins .= " user_{$thing}.{$thing}_id IN $in_vals "; 
    $result = mysql_query($query2)  or trigger_error("Query: $query2\n<br />MySQL Error: " . mysql_error());
    $chosen_things = null;
    while ($row=mysql_fetch_array($result)) { // bung them into an array
      $chosen_things[] = $row[0];
    }
    $do_search = TRUE;
    return $chosen_things;
  }
}

function output_user_info($user_id) {
  $name = fetch_user_name($user_id);
  echo "<dl><dt>$name[0] $name[1]</dt>\n";

  $result = fetch_user_thing_results('subject', $user_id, 1);
  output_user_thing_results($result, 'Undergraduate subjects');

  $result = fetch_user_thing_results('subject', $user_id, 2);
  output_user_thing_results($result, 'Postgraduate subjects');

  $result = fetch_user_thing_results('interest', $user_id, 1);
  output_user_thing_results($result, 'Occupation/expertise');

  $result = fetch_user_thing_results('advice', $user_id, 1);
  output_user_thing_results($result, 'Types of advice');

  $blurb = fetch_user_blurb($user_id);
  echo "<dd class=\"expertise\">$blurb[0]</dd>\n";

  if ($name[2]) { // allowed to contact
    echo "<dd><a href=\"sendMessage.php?assoc=$user_id\">Contact</a></dd></dl>\n";
  }
}

function output_user_thing_results($result, $desc) {
  if (mysql_num_rows($result) > 0) {
    echo "<dd>$desc:";
    $first = TRUE;
    while ($row=mysql_fetch_array($result)) {
      if (! $first) { echo ",";}
      echo " $row[0]";
      $first = FALSE;
    }
    echo "</dd>\n";
  }
}

function output_chosen_things($things, $desc) {
  if (count($things) > 0) {
    echo "<li>$desc: ";
    $first = TRUE;
    foreach ($things as $subj) {
      if (! $first) { echo ",";}
      echo " $subj";
      $first = FALSE;
    }
    echo "</li>\n";
  }
}

?>

